import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { Select, Button, Row, Radio, Col, Input, Card, Form, message, Checkbox } from 'antd';
import { request_func } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { MainCard } from "src/business/components/style-components/main-card";
import { FileUploadBtn } from "src/business/components/buss-components/file-operation-btn/file-upload-btn";
import { remote } from "src/projects/remote";
import { beforeUpload } from "src/projects/app/util-tool";
import TextArea from "antd/lib/input/TextArea";
import { MainContent } from "src/business/components/style-components/main-content";
import { ROUTE_PATH } from "src/projects/router";
/**
 * 组件：更换房间页面
 */
export interface RoomChangeViewState extends ReactViewState {
    /** 基础数据 */
    base_data?: {};
    /** 项目列表集合 */
    all_item_list?: any[];
    /** 床位 */
    bed_list?: any[];
    /** 项目列表 */
    item_list?: any[];
    /** 登记成功时间 */
    create_date: string;
    /** 长者信息 */
    user_info?: object;
    /** 入住评估 */
    evaluation_info?: object;
    /** 用户的id */
    user_id?: any;
    /** 床位id */
    bed_id?: any;
    /** 弹窗用服务产品id + 床位Id字段 */
    service_product_and_bed_id?: string;
    backPath?: any;
}
export interface ServiceItemPackageFormValues {
    id?: string;
}
/**
 * 组件：更换房间页面
 * 描述
 */
export class RoomChangeView extends ReactView<RoomChangeViewControl, RoomChangeViewState> {
    constructor(props: RoomChangeViewControl) {
        super(props);
        this.state = {
            base_data: {},
            all_item_list: [],
            bed_list: [],
            item_list: [],
            create_date: '',
            user_info: {},
            evaluation_info: {},
            user_id: '',
            bed_id: '',
            service_product_and_bed_id: ''
        };
    }
    componentDidMount() {
        console.info('初始化', this.props);
        const url = this.props.showOld ? 'get_bed_list' : 'get_bed_list_no_user';
        this.setState({
            backPath: this.props.backPath ? this.props.backPath : ROUTE_PATH.roomList
        });
        // 床位列表
        request_func(this, AppServiceUtility.hotel_zone_type_service[url], [{}], (data: any) => {
            this.setState({
                bed_list: data.result
            });
        });
        if (this.props && this.props.match && this.props.match!.params && this.props.match!.params.key) {
            // 这是正常页面调用情况
            // 根据传过来的id去check_in表里面找到用的的id
            request_func(this, AppServiceUtility.check_in_service.get_check_in_list, [{ "id": this.props.match!.params.key }, 1, 1], (data: any) => {
                // console.log("拿到用户的id>>>>>>>>>", data);
                this.setState({
                    user_id: data.result[0].user_id
                });
            });
        } else {
            // 这是弹窗调用传参情况
            this.setState({
                user_id: this.props.user_id
            });
        }
        // 弹窗根据床位id，查询服务产品Id
        if (this.props.bed_id) {
            request_func(this, AppServiceUtility.hotel_zone_type_service[url], [{ "id": this.props.bed_id }], (data: any) => {
                if (data.result.length > 0) {
                    this.setState({
                        service_product_and_bed_id: data.result[0].service_item_package_id + ',' + data.result[0].id
                    });
                    this.bedOnChange(data.result[0].service_item_package_id + ',' + data.result[0].id, null);
                }
            });
        }
    }
    /** 提交 */
    handleSubmitService = (e: any) => {
        e.preventDefault();
        const { form } = this.props;
        form!.validateFields((err: Error, values: ServiceItemPackageFormValues) => {
            let serviceValue = {};
            let service_item: any = [];
            let details: any = [];
            this.state.all_item_list!.map((item) => {
                service_item.push({ service_options: [] });
                let detail = {
                    product_id: item.product_id,
                    product_name: item.product_name,
                    valuation_formula: item.valuation_formula,
                    service_option: [],
                    contract_terms: item.contract_terms,
                    count: 1,
                };
                details.push(detail);
            });
            for (let key in values) {
                if (key.indexOf('___') !== -1) {
                    console.log('keys', key);
                    let keys = key.split('___');
                    if (keys[0] === 'service_item' || keys[0] === 'service_type') {
                        service_item[parseInt(keys[1], undefined)][keys[0]] = values[key];
                    } else {
                        details.map((item: any) => {
                            console.log('aaa', item, item.product_id, keys[0]);
                            if (item.product_id === keys[0]) {
                                let option_values = values[key].split('___');
                                let option = {
                                    name: keys[1],
                                    option_value: option_values[0],
                                    option_type: keys[2] || '',
                                };
                                item['service_option'].push(option);
                            }
                        });
                    }

                } else {
                    serviceValue[key] = values[key];
                }
            }
            const service_info: object = {
                user_id: this.state.user_id,
                // service_item: service_item,
                service_provider_id: this.state.base_data ? this.state.base_data['org_id'] : '', // 获取服务提供者
                new_bed_id: this.state.bed_id, // 床位id
                detail: details,
            };

            request_func(this, AppServiceUtility.accommodation_process_service.change_room_process, [service_info, this.props.noChangeBed], (data: any) => {
                if (data === 'Success') {
                    message.info('调整成功');
                    if (this.props.bed_id && this.props.bed_id !== '') {
                        // 弹窗
                        this.props.back_fuc && this.props.back_fuc!();
                        this.props.backPath && this.props.history!.push(this.state.backPath);
                    } else {
                        this.props.history!.push(this.state.backPath);
                    }
                } else {
                    message.error(data);
                }
            });
        });
    }
    bedOnChange = (value: any, option: any) => {
        console.log('value>>>', value);
        // 分割出服务包id和床位id
        const ids = value.split(",");
        // 根据id获取服务包
        request_func(this, AppServiceUtility.service_item_package.get_service_item_package, [{ id: ids[0] }, 1, 999], (data: any) => {

            // data!.result![0]['bed_id'] = ids[1];
            this.setState({
                bed_id: ids[1],
                base_data: data!.result![0],
                // all_item_list: data!.result![0]['item'],
            });
            // 根据服务包id获取包下的所以服务项目
            request_func(this, AppServiceUtility.services_project_service.get_all_item_from_product, [{ 'id': data!.result![0]['id'], "is_service_item": data!.result![0]['is_service_item'] }, 1, 9999], (data: any) => {

                this.setState({
                    all_item_list: data.result,
                });
            });
        });
        // console.info(this.state.base_data, this.state.all_item_list);
    }
    /** 选择服务产品值改变事件 */
    itemOnChange = (value: any, option: any) => {
        let list: any[] = this.state.all_item_list!;
        // 根据传过来的id获取产品下的服务项目
        AppServiceUtility.services_project_service.get_services_project_list!({ id: value })!
            .then((data: any) => {
                console.log('-----------data', data);
                if (list.length > 0 && data) {
                    list[option.key] = data.result[0];
                    this.setState({
                        all_item_list: list
                    });
                }
            });
    }
    render() {
        const { getFieldDecorator } = this.props.form!;
        let item_list;
        if (this.state.all_item_list && this.state.all_item_list!.length > 0) {
            console.log('====================', this.state.all_item_list);
            item_list = this.state.all_item_list!.map((value, index) => {
                console.info('fjdssds>>>>>>>>>>>>>>.', index, value);
                return (
                    <Card key={index}>
                        <Row type="flex" justify="center">
                            <Col span={12}>
                                <Form.Item label='服务产品'>
                                    {getFieldDecorator('service_item___' + index, {
                                        initialValue: value.name ? value.name : '',
                                        rules: [{
                                            message: '请选择服务产品'
                                        }],
                                    })(
                                        <Select showSearch={true} key={index} onChange={this.itemOnChange} disabled={true}>
                                            {this.state.item_list!.map((key) => {
                                                return <Select.Option key={index} value={key['id']}>{key['name']}</Select.Option>;
                                            })}
                                        </Select>
                                    )}
                                </Form.Item>
                                {
                                    // let vf = value.valuation_formula ? value.valuation_formula : (value.valuation_formula ? value.valuation_formula : value.valuation_formula);
                                    value.valuation_formula ? (
                                        <Form.Item label='计价方式'>
                                            {getFieldDecorator('valuation_formula___' + '0', {
                                                initialValue: value.valuation_formula ? value.valuation_formula[0].name : "",
                                                rules: [{
                                                    required: false,
                                                    message: '请选择计价方式'
                                                }],
                                                option: {
                                                    disabled: true,
                                                    placeholder: '请选择计价方式'
                                                }
                                            })(
                                                <Select disabled={true}>
                                                    <Select.Option key={0} value={value.valuation_formula}>{value.valuation_formula.name}</Select.Option>
                                                </Select>
                                            )}
                                        </Form.Item>
                                    ) : ''
                                }
                                {
                                    value.type_name ? (
                                        <Form.Item label='服务类型'>
                                            {getFieldDecorator('service_type___' + 0, {
                                                initialValue: value.item_type ? value.item_type : "",
                                                rules: [{
                                                    required: false,
                                                }],
                                                option: {
                                                    disabled: true
                                                }
                                            })(
                                                <Select disabled={true}>
                                                    <Select.Option key={value.item_type} >{value.type_name}</Select.Option>
                                                </Select>
                                            )}
                                        </Form.Item>
                                    ) : ''
                                }
                                {(() => {
                                    if (!value.service_option) {
                                        return null;
                                    }
                                    return value.service_option.map((service_option: any, indexs: any) => {
                                        if (service_option.option_type === 'service_after') {
                                            return (
                                                <Row style={{ display: 'none' }}>
                                                    <Form.Item label={service_option.name} key={indexs}>
                                                        {getFieldDecorator(value.product_id + '___' + service_option.name + '___' + service_option.option_type, {
                                                            initialValue: service_option.option_value || (service_option.default_value || ''),
                                                            rules: [{
                                                                required: false,
                                                            }],
                                                        })(
                                                            <Input type="hidden" />
                                                        )}
                                                    </Form.Item>
                                                </Row>
                                            );
                                        }
                                        if (service_option.option_value_type === '1') {
                                            return (
                                                <Form.Item label={service_option.name} key={indexs}>
                                                    {getFieldDecorator(value.product_id + '___' + service_option.name + '___' + service_option.option_type, {
                                                        initialValue: service_option.option_value || (service_option.default_value || ''),
                                                        rules: [{
                                                            required: false,
                                                        }],
                                                    })(
                                                        <Radio.Group>
                                                            {
                                                                service_option.option_content!.map((item: any, content: any) => {
                                                                    return <Radio key={content} value={item.option_value}>{item.option_content}</Radio>;
                                                                })
                                                            }
                                                        </Radio.Group>
                                                    )}
                                                </Form.Item>
                                            );
                                        } else if (service_option.option_value_type === '2') {
                                            return (
                                                <Form.Item label={service_option.name} key={indexs}>
                                                    {getFieldDecorator(value.product_id + '___' + service_option.name + '___' + service_option.option_type, {
                                                        initialValue: service_option.option_value || (service_option.default_value || ''),
                                                        rules: [{
                                                            required: false,
                                                        }],
                                                    })(
                                                        <Checkbox.Group>
                                                            {
                                                                service_option.option_content!.map((item: any, idx: any) => {
                                                                    return <Checkbox key={idx} value={item.option_value}>{item.option_content}</Checkbox>;
                                                                })
                                                            }
                                                        </Checkbox.Group>
                                                    )}
                                                </Form.Item>
                                            );
                                        } else if (service_option.option_value_type === '3') {
                                            return (
                                                <Form.Item label={service_option.name} key={indexs}>
                                                    {getFieldDecorator(value.product_id + '___' + service_option.name + '___' + service_option.option_type, {
                                                        initialValue: service_option.option_value || (service_option.default_value || ''),
                                                        rules: [{
                                                            required: false,
                                                        }],
                                                    })(
                                                        <Input />
                                                    )}
                                                </Form.Item>
                                            );
                                        } else {
                                            return null;
                                        }
                                    });
                                })()}
                                {
                                    // value.service_option ? value.service_option.map((service_options: any, indexs: any) => {
                                    //     return service_options.option_type  ? (
                                    //         <Form.Item label={service_options.name} key={indexs}>
                                    //             {getFieldDecorator(value.product_id + '___' + indexs, {
                                    //                 initialValue: service_options.value ? service_options.value : '',
                                    //                 rules: [{
                                    //                     required: false,
                                    //                 }],
                                    //             })(
                                    //                 <Radio.Group>
                                    //                     {
                                    //                         service_options.option_content ? service_options.option_content!.map((item: any, content: any) => {
                                    //                             return <Radio key={content} value={service_options.name + '___' + item.option_value + '___' + service_options.option_type}>{item.option_content}</Radio>;
                                    //                         }) : <Radio key={0} value={service_options.name + '___' + service_options.default_value + '___' + service_options.option_type}>{service_options.default_value}</Radio>
                                    //                     }
                                    //                 </Radio.Group>
                                    //             )}
                                    //         </Form.Item>
                                    //     ) : '';
                                    // }) : ''
                                }
                            </Col>
                        </Row>
                    </Card >
                );
            });
        }
        return (
            <Form onSubmit={this.handleSubmitService}>
                <MainContent>
                    <MainCard title='服务产品'>
                        <Row type="flex" justify="center">
                            <Col span={12}>
                                <Form.Item label='床位'>
                                    {getFieldDecorator('service_item_package_id', {
                                        rules: [{
                                            message: '请选择床位',
                                        }],
                                        initialValue: this.state.service_product_and_bed_id ? this.state.service_product_and_bed_id : '',// 这里主要是赋值弹窗传入的床位id去找到的服务产品id
                                    })(
                                        <Select showSearch={true} onChange={this.bedOnChange} disabled={this.props.noChangeBed}>
                                            {
                                                this.state.bed_list!.map((option) => {
                                                    return (<Select.Option key={option.service_item_package_id + ',' + option.id}>{option.name}</Select.Option>);
                                                })
                                            }

                                        </Select>
                                    )}
                                </Form.Item>
                                <Form.Item label='服务产品名称'>
                                    {getFieldDecorator('name', {
                                        initialValue: this.state.base_data ? this.state.base_data['name'] : '',
                                    })(
                                        <Input disabled={true} />
                                    )}
                                </Form.Item>
                                {/* <Form.Item label='是否启用'>
                                    {getFieldDecorator('state', {
                                        initialValue: this.state.base_data ? this.state.base_data['state'] : [],
                                    })(
                                        <Radio.Group disabled={true}>
                                            <Radio value={"1"}>启用</Radio>
                                            <Radio value={"0"}>停用</Radio>
                                        </Radio.Group>
                                    )}
                                </Form.Item> */}
                                <Form.Item label='所属组织机构'>
                                    {getFieldDecorator('organization_name', {
                                        initialValue: this.state.base_data ? this.state.base_data['organizational_name'] : '',
                                    })(
                                        <Input disabled={true} />
                                    )}
                                </Form.Item>
                                <Form.Item label='服务包图片'>
                                    {getFieldDecorator('picture_collection', {
                                        initialValue: this.state.base_data!['picture_collection'] ? this.state.base_data!['picture_collection'] : '',
                                    })(
                                        <FileUploadBtn list_type={"picture-card"} contents={"plus"} action={remote.upload_url} beforeUpload={beforeUpload} upload_amount={0} />
                                    )}
                                </Form.Item>
                                <Form.Item label='附加合同条款'>
                                    {getFieldDecorator('additonal_contract_terms', {
                                        initialValue: this.state.base_data ? this.state.base_data['additonal_contract_terms'] : '',
                                    })(
                                        <TextArea rows={4} disabled={true} />
                                    )}
                                </Form.Item>
                                <Form.Item label='服务产品介绍'>
                                    {getFieldDecorator('service_product_introduce', {
                                        initialValue: this.state.base_data ? this.state.base_data['service_product_introduce'] : '',
                                    })(
                                        <TextArea rows={4} disabled={true} />
                                    )}
                                </Form.Item>
                                {/* <Form.Item label='是否服务项目'>
                                    {getFieldDecorator('is_service_item', {
                                        initialValue: this.state.base_data!['is_service_item'] ? this.state.base_data!['is_service_item'] : '',
                                    })(
                                        <Select showSearch={true} disabled={true}>
                                            <Option value="true">是</Option>
                                            <Option value="false">否</Option>
                                        </Select>
                                    )}
                                </Form.Item> */}
                            </Col>
                        </Row>
                    </MainCard>
                    <MainCard title='服务项目清单'>
                        {item_list}
                    </MainCard>
                    <Row type="flex" justify="center">
                        {
                            !this.state.bed_id ?
                                <Button htmlType='submit' onClick={() => { this.props.history!.push(this.state.backPath); }}>取消</Button>
                                : null
                        }
                        {
                            this.props.backPath ?
                                <Button htmlType='submit' onClick={() => { this.props.history!.push(this.state.backPath); }}>返回</Button>
                                : null
                        }
                        <Button htmlType='submit' type='primary'>提交</Button>
                    </Row>
                </MainContent>
            </Form>
        );
    }
}

/**
 * 控件：更换房间页面
 * 描述
 */
@addon(' RoomChangeView', '更换房间页面', '提示')
@reactControl(Form.create<any>()(RoomChangeView), true)
export class RoomChangeViewControl extends ReactViewControl {
    /** 用户id */
    user_id?: string;
    /** 床位Id */
    bed_id?: string;
    /** 提交后回调 */
    back_fuc?: Function;
    form?: any;
    /** 是否显示原床位-产品信息 */
    showOld?: boolean;
    /** 是否不能编辑床位 */
    noChangeBed?: boolean;
    /** 提交之后返回的路径 */
    backPath?: string;
    history?: any;
}